// antd组件依赖
import { Card, Breadcrumb, Input, Space, Button, Popconfirm, Table, message, Tooltip } from 'antd';



import { HomeOutlined, UserOutlined } from '@ant-design/icons';
import React, { useEffect, useState } from "react";

import { useOrder } from '../../hook/order';





// 搜索框依赖
const { Search } = Input;


// eslint-disable-next-line
export default () => {

  const [selectData, setSelect] = useState();

  const [{ rows, total, eachPage, curPage }, { getOrder, setCurPage, setEachPage, delOrder, findOrder, changeState }] = useOrder();
  console.log(rows);
  // 表格依赖
  const columns = [
    {
      title: '订单id',
      dataIndex: '_id',
      key: '_id',

    },
    {
      title: "用户",
      dataIndex: 'userId',
      key: 'userId',
      render: (text, record) => {
        return <span>{text?.username}</span>
      }
    },
    {
      title: "用户id",
      dataIndex: 'userId',
      key: 'userId',
      render: (text, record) => {
        return <span>{text._id}</span>
      }
    },
    {
      title: '下单时间',
      dataIndex: 'orderTime',
      key: 'orderTime',

    },
    {
      title: '总价',
      dataIndex: 'totalPrice',
      key: 'totalPrice',
    },

    {
      title: "是否收货",
      dataIndex: 'isAffirmReceive',
      key: 'isAffirmReceive',
      render: (text, record) => {
        if (text) {
          return <span>是</span>
        };
        return <span>否</span>
      }
    },
    {
      title: '操作',
      key: 'action',
      render: (text, record) => {
        if (record.isAffirmReceive) {
          return (
            <Space size="middle">
              <Button shape="round" type="primary" disabled>已收货</Button >
              <Popconfirm title="确定删除？" okText="Yes" cancelText="No" onConfirm={() => handleDelete(record._id)}  >
                <Button shape="round" type="primary" danger>删除</Button >
              </Popconfirm>
            </Space >
          )
        }
        return (
          <Space size="middle">
            <Popconfirm title="确定收货？" okText="Yes" cancelText="No" onConfirm={() => onChangState(record._id)}  >
              <Button shape="round" type="primary" >确认收货</Button >
            </Popconfirm>
            <Popconfirm title="确定删除？" okText="Yes" cancelText="No" onConfirm={() => handleDelete(record._id)}  >
              <Button shape="round" type="primary" danger>删除</Button >
            </Popconfirm>
          </Space >
        )

      },
    },
  ];



  // 表格展开的子表格，接收参数：当前行的整条数据
  const expandedRowRender = (record) => {
    const columns = [
      { title: '商品名', dataIndex: 'name', key: 'name' },
      { title: '单价', dataIndex: 'price', key: 'price' },
      { title: '已售', dataIndex: 'sold', key: 'sold' },
      { title: '库存', dataIndex: 'total', key: 'total' },
      { title: '限购', dataIndex: 'restricted', key: 'restricted' },
      { title: '购买数量', dataIndex: 'count', key: 'count' },
    ];

    const data = [];
    for (let i = 0; i < record.commodities.length; i++) {
      data.push({
        key: i,
        name: record.commodities[i].seckill_id.name,
        price: record.commodities[i].seckill_id.Price,
        sold: record.commodities[i].seckill_id.Sold,
        total: record.commodities[i].seckill_id.Total,
        restricted: record.commodities[i].seckill_id.restricted,
        count: record.commodities[i].count,
      });
    }
    return <Table columns={columns} dataSource={data} pagination={false} />;
  };


  // 结构渲染完成后获取数据
  useEffect(() => {
    getOrder()
  }, [getOrder]);

  // 删除确认按钮方法
  const handleDelete = async (_id) => {
    await delOrder(_id);
    message.success({ content: "删除成功" });
    getOrder();
  };

  // 通过商品和id名称查询订单
  const onSearch = async () => {
    const { usersIdResult } = await findOrder(selectData);
    console.log(usersIdResult);
    // 查询userId有值，后天则判断是否为有效id，
    // 如有效则后台返回usersIdResult为undefined，
    // 如传值 但传入的userId值无效，则后台返回usersIdResult值为void，
    if (usersIdResult) message.error("输入的id无效");
  };

  // 确认收货
  const onChangState = async (_id) => {
    await changeState(_id);
    message.success(`收货成功`);
    getOrder();
  }

  // 查询的用户id添加到状态
  const onChange = (e) => {
    // 将需要查询的数据合并到状态
    setSelect({ ...selectData, userId: e.target.value });
  }
  // 查询的商品名数据添加到状态
  const onChange1 = (e) => {
    setSelect({ ...selectData, searchName: e.target.value });
  }


  return (
    <div>
      {/* 头部 */}
      < Card >
        {/* 面包屑导航 */}
        < Breadcrumb >
          <Breadcrumb.Item href="/#/info">
            <HomeOutlined />
          </Breadcrumb.Item>
          <Breadcrumb.Item>
            <UserOutlined />
            <span>order</span>
          </Breadcrumb.Item>
          <Breadcrumb.Item>order List</Breadcrumb.Item>
        </Breadcrumb >
        <div style={{ height: 20 }}></div>
        {/* 搜索框 */}
        <Input placeholder="需查询用户id（选填）" style={{ width: 200 }} onChange={onChange} />

        {/* 搜索框 */}
        <Input placeholder="需查询商品名（选填）" onChange={onChange1} style={{ width: 200, marginLeft: 10, marginRight: 10 }} />
        <Button type="primary" onClick={onSearch}>查询</Button>
      </Card >


      {/* 订单表格 */}
      < Card >
        <Table
          columns={columns}
          dataSource={rows}
          expandable={{ expandedRowRender }}
          rowKey={(record) => record._id}
          pagination={{
            total,
            current: curPage,
            pageSize: eachPage,
            showQuickJumper: true,
            showSizeChanger: true,
            pageSizeOptions: ['1', '2', '5'],
            onChange: (curPage, eachPage) => {
              setCurPage(curPage);
              setEachPage(eachPage);
            },

          }}
        />
      </Card >
    </div>
  )
}